/*
 * Copyright (c) 2020 Tenny
 *  typescript-init is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *           http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

const readline = require('readline');
const Confirm = require('./ui/confirm');
const Input = require('./ui/input');

const uis = {
  confirm: Confirm,
  input: Input
}

/**
 * 渲染交互UI
 * @param {Object} prompt 配置
 * @param {Object} rl     ReadlineInterface
 * @param {Function} cb   回调
 */
function render (prompt, rl, cb) {
  new uis[prompt.type](rl, prompt, cb);
}

/**
 * 展示问答选项
 * @param {Array[Object]} promptList 问答列表
 *  通用配置项：
 *    name - 存储当前问题回答的变量
 *    type - 表示提问的类型，包括：confirm
 *    default - 默认值
 */
function prompt (promptList) {
  return new Promise((resolve, reject) => {
    if (promptList instanceof Array) {
      let length = promptList.length;
      if (length > 0) {
        let rl = readline.createInterface({
          input: process.stdin,
          output: process.stdout
        });
        let values = {}, index = 0;
        let callback = function(name, value) {
          values[name] = value;
          index++;
          if (index === length) {
            rl.close();
            rl = null;
            resolve(values);
          } else {
            render(promptList[index], rl, callback);
          }
        }
        render(promptList[index], rl, callback);
      } else {
        resolve({});
      }
    } else {
      reject(new Error('不支持的 Prompt 配置'))
    }
  }); 
}

module.exports = {
  prompt
}